import React, { useEffect } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { RootState } from '../store';

interface PrivateRouteProps {
  children: React.ReactNode;
  requiredRole?: number;
}

const PrivateRoute: React.FC<PrivateRouteProps> = ({ children, requiredRole = 1 }) => {
  const location = useLocation();
  const user = useSelector((state: RootState) => state.auth.user);
  const userRole = user?.role || 0;

  // 添加调试日志
  useEffect(() => {
    console.log('PrivateRoute auth check:', {
      path: location.pathname,
      user,
      userRole,
      requiredRole,
      isAuthenticated: !!user,
      hasRequiredRole: userRole >= requiredRole,
      timestamp: new Date().toISOString()
    });
  }, [location.pathname, user, userRole, requiredRole]);

  // 用户未登录，重定向到登录页
  if (!user) {
    console.log('User not authenticated, redirecting to login');
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  // 用户权限不足，重定向到个人资料页
  if (userRole < requiredRole) {
    console.log(`Insufficient permissions: user role ${userRole} < required role ${requiredRole}`);
    return <Navigate to="/profile" replace />;
  }

  // 用户已认证且具有足够权限
  console.log('Access granted to protected route');
  return <>{children}</>;
};

export default PrivateRoute;